/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import pojos.Exporter;
import dao.exceptions.NonexistentEntityException;
import dao.exceptions.PreexistingEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import pojos.ExporterItem;
import java.util.ArrayList;
import java.util.Collection;
import pojos.Bill;
import javax.transaction.UserTransaction;

/**
 *
 * @author A7med Kotb
 */
public class ExporterJpaController implements Serializable {

    public ExporterJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Exporter exporter) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (exporter.getExporterItemCollection() == null) {
            exporter.setExporterItemCollection(new ArrayList<ExporterItem>());
        }
        if (exporter.getBillCollection() == null) {
            exporter.setBillCollection(new ArrayList<Bill>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Collection<ExporterItem> attachedExporterItemCollection = new ArrayList<ExporterItem>();
            for (ExporterItem exporterItemCollectionExporterItemToAttach : exporter.getExporterItemCollection()) {
                exporterItemCollectionExporterItemToAttach = em.getReference(exporterItemCollectionExporterItemToAttach.getClass(), exporterItemCollectionExporterItemToAttach.getIdExporterItem());
                attachedExporterItemCollection.add(exporterItemCollectionExporterItemToAttach);
            }
            exporter.setExporterItemCollection(attachedExporterItemCollection);
            Collection<Bill> attachedBillCollection = new ArrayList<Bill>();
            for (Bill billCollectionBillToAttach : exporter.getBillCollection()) {
                billCollectionBillToAttach = em.getReference(billCollectionBillToAttach.getClass(), billCollectionBillToAttach.getIdBill());
                attachedBillCollection.add(billCollectionBillToAttach);
            }
            exporter.setBillCollection(attachedBillCollection);
            em.persist(exporter);
            for (ExporterItem exporterItemCollectionExporterItem : exporter.getExporterItemCollection()) {
                Exporter oldExporterIDOfExporterItemCollectionExporterItem = exporterItemCollectionExporterItem.getExporterID();
                exporterItemCollectionExporterItem.setExporterID(exporter);
                exporterItemCollectionExporterItem = em.merge(exporterItemCollectionExporterItem);
                if (oldExporterIDOfExporterItemCollectionExporterItem != null) {
                    oldExporterIDOfExporterItemCollectionExporterItem.getExporterItemCollection().remove(exporterItemCollectionExporterItem);
                    oldExporterIDOfExporterItemCollectionExporterItem = em.merge(oldExporterIDOfExporterItemCollectionExporterItem);
                }
            }
            for (Bill billCollectionBill : exporter.getBillCollection()) {
                Exporter oldExporterIDOfBillCollectionBill = billCollectionBill.getExporterID();
                billCollectionBill.setExporterID(exporter);
                billCollectionBill = em.merge(billCollectionBill);
                if (oldExporterIDOfBillCollectionBill != null) {
                    oldExporterIDOfBillCollectionBill.getBillCollection().remove(billCollectionBill);
                    oldExporterIDOfBillCollectionBill = em.merge(oldExporterIDOfBillCollectionBill);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findExporter(exporter.getIdExporter()) != null) {
                throw new PreexistingEntityException("Exporter " + exporter + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Exporter exporter) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Exporter persistentExporter = em.find(Exporter.class, exporter.getIdExporter());
            Collection<ExporterItem> exporterItemCollectionOld = persistentExporter.getExporterItemCollection();
            Collection<ExporterItem> exporterItemCollectionNew = exporter.getExporterItemCollection();
            Collection<Bill> billCollectionOld = persistentExporter.getBillCollection();
            Collection<Bill> billCollectionNew = exporter.getBillCollection();
            Collection<ExporterItem> attachedExporterItemCollectionNew = new ArrayList<ExporterItem>();
            for (ExporterItem exporterItemCollectionNewExporterItemToAttach : exporterItemCollectionNew) {
                exporterItemCollectionNewExporterItemToAttach = em.getReference(exporterItemCollectionNewExporterItemToAttach.getClass(), exporterItemCollectionNewExporterItemToAttach.getIdExporterItem());
                attachedExporterItemCollectionNew.add(exporterItemCollectionNewExporterItemToAttach);
            }
            exporterItemCollectionNew = attachedExporterItemCollectionNew;
            exporter.setExporterItemCollection(exporterItemCollectionNew);
            Collection<Bill> attachedBillCollectionNew = new ArrayList<Bill>();
            for (Bill billCollectionNewBillToAttach : billCollectionNew) {
                billCollectionNewBillToAttach = em.getReference(billCollectionNewBillToAttach.getClass(), billCollectionNewBillToAttach.getIdBill());
                attachedBillCollectionNew.add(billCollectionNewBillToAttach);
            }
            billCollectionNew = attachedBillCollectionNew;
            exporter.setBillCollection(billCollectionNew);
            exporter = em.merge(exporter);
            for (ExporterItem exporterItemCollectionOldExporterItem : exporterItemCollectionOld) {
                if (!exporterItemCollectionNew.contains(exporterItemCollectionOldExporterItem)) {
                    exporterItemCollectionOldExporterItem.setExporterID(null);
                    exporterItemCollectionOldExporterItem = em.merge(exporterItemCollectionOldExporterItem);
                }
            }
            for (ExporterItem exporterItemCollectionNewExporterItem : exporterItemCollectionNew) {
                if (!exporterItemCollectionOld.contains(exporterItemCollectionNewExporterItem)) {
                    Exporter oldExporterIDOfExporterItemCollectionNewExporterItem = exporterItemCollectionNewExporterItem.getExporterID();
                    exporterItemCollectionNewExporterItem.setExporterID(exporter);
                    exporterItemCollectionNewExporterItem = em.merge(exporterItemCollectionNewExporterItem);
                    if (oldExporterIDOfExporterItemCollectionNewExporterItem != null && !oldExporterIDOfExporterItemCollectionNewExporterItem.equals(exporter)) {
                        oldExporterIDOfExporterItemCollectionNewExporterItem.getExporterItemCollection().remove(exporterItemCollectionNewExporterItem);
                        oldExporterIDOfExporterItemCollectionNewExporterItem = em.merge(oldExporterIDOfExporterItemCollectionNewExporterItem);
                    }
                }
            }
            for (Bill billCollectionOldBill : billCollectionOld) {
                if (!billCollectionNew.contains(billCollectionOldBill)) {
                    billCollectionOldBill.setExporterID(null);
                    billCollectionOldBill = em.merge(billCollectionOldBill);
                }
            }
            for (Bill billCollectionNewBill : billCollectionNew) {
                if (!billCollectionOld.contains(billCollectionNewBill)) {
                    Exporter oldExporterIDOfBillCollectionNewBill = billCollectionNewBill.getExporterID();
                    billCollectionNewBill.setExporterID(exporter);
                    billCollectionNewBill = em.merge(billCollectionNewBill);
                    if (oldExporterIDOfBillCollectionNewBill != null && !oldExporterIDOfBillCollectionNewBill.equals(exporter)) {
                        oldExporterIDOfBillCollectionNewBill.getBillCollection().remove(billCollectionNewBill);
                        oldExporterIDOfBillCollectionNewBill = em.merge(oldExporterIDOfBillCollectionNewBill);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = exporter.getIdExporter();
                if (findExporter(id) == null) {
                    throw new NonexistentEntityException("The exporter with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Exporter exporter;
            try {
                exporter = em.getReference(Exporter.class, id);
                exporter.getIdExporter();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The exporter with id " + id + " no longer exists.", enfe);
            }
            Collection<ExporterItem> exporterItemCollection = exporter.getExporterItemCollection();
            for (ExporterItem exporterItemCollectionExporterItem : exporterItemCollection) {
                exporterItemCollectionExporterItem.setExporterID(null);
                exporterItemCollectionExporterItem = em.merge(exporterItemCollectionExporterItem);
            }
            Collection<Bill> billCollection = exporter.getBillCollection();
            for (Bill billCollectionBill : billCollection) {
                billCollectionBill.setExporterID(null);
                billCollectionBill = em.merge(billCollectionBill);
            }
            em.remove(exporter);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Exporter> findExporterEntities() {
        return findExporterEntities(true, -1, -1);
    }

    public List<Exporter> findExporterEntities(int maxResults, int firstResult) {
        return findExporterEntities(false, maxResults, firstResult);
    }

    private List<Exporter> findExporterEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Exporter.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Exporter findExporter(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Exporter.class, id);
        } finally {
            em.close();
        }
    }

    public int getExporterCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Exporter> rt = cq.from(Exporter.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
